const { default: commonjs } = require("@rollup/plugin-commonjs");
const { default: nodeResolve } = require("@rollup/plugin-node-resolve");
const { babel } = require("@rollup/plugin-babel");
const { default: terser } = require("@rollup/plugin-terser");
const postcss = require("rollup-plugin-postcss");
const vue = require("rollup-plugin-vue");
const replace = require("rollup-plugin-replace");
const serve = require("rollup-plugin-serve");
const livereload = require("rollup-plugin-livereload");

const isProd = process.env.NODE_ENV === "production";

const plugins = [
  commonjs(), // 默认loadsh没有打包时因为使用commonjs，rollup默认情况下只会处理es module
  nodeResolve(),
  babel({
    babelHelpers: "bundled",
    exclude: /node_modules/,
  }),
  postcss(),
  vue(),
  replace({
    // vue中打包需要注入的变量
    "process.env.NODE_ENV": JSON.stringify("production"),
  }),
];

if (isProd) {
  plugins.push(terser());
} else {
  const devPlugins = [
    serve({
      open: true,
      port: 8080,
      contentBase: ".",
    }),
    livereload(), // 文件发生变化时，自动刷新浏览器
  ];
  plugins.push(...devPlugins);
}

module.exports = {
  input: "./src/index.js",
  output: [
    {
      format: "umd",
      name: "whyUtils",
      file: "./build/bundle.umd.js",
      globals: {
        lodash: "_",
      },
    },
  ],
  external: ["lodash"],
  plugins: plugins,
};
